<template>
  <div>
    <div class="carHead">
      <div class="carHead_left">购物车</div>
      <div class="carHead_right">
        <span @click="changeBtnState">管理</span>
      </div>
    </div>
    <div v-if="shopCarData == null" class="empty">
      <van-empty
        class="custom-image"
        image="https://img01.yzcdn.cn/vant/custom-empty-image.png"
        image-size="40vw"
      >
        <p>购物车是空的</p>
        <van-button round to="/typecake" type="danger" class="bottom-button"
          >去逛逛</van-button
        >
      </van-empty>
    </div>
    <div v-else class="carContent" ref="checkboxGroup">
      <div class="carItem" v-for="(item, i) in shopCarData" :key="item.shop_id">
        <div class="carItem_left">
          <div class="carItem_left_img">
            <img :src="item.cake_pic" alt="" />
          </div>
          <div class="carItem_left_content">
            <ul>
              <li class="title">{{ item.cake_title }}</li>
              <li class="specs">
                规格：{{ item.size }}&nbsp;{{ item.sandwich }}&nbsp;{{
                  item.composition
                }}
              </li>
              <li class="cake_price">
                ¥&nbsp;{{ getPrice(item.price, item.shop_count) }}
              </li>
            </ul>
          </div>
        </div>
        <div class="catItem_right">
          <div class="sel_items">
            <van-checkbox
              v-model="item.ischecked"
              icon-size="5vw"
              checked-color="#ffd100"
              @click="toAddTotal(i)"
            ></van-checkbox>
          </div>
          <div class="sel_specs_num_change">
            <span @click="subCount(item.shop_id, i, $event)">-</span>
            <span>{{ item.shop_count }}</span>
            <span @click="addCount(item.shop_id, i, $event)">+</span>
          </div>
        </div>
      </div>
    </div>

    <div class="controlBottom">
      <div class="controlCar" v-if="shopCarData != null">
        <div class="controlCar_left">
          <van-checkbox
            class="allSel"
            v-show="true"
            v-model="checked"
            icon-size="5vw"
            checked-color="#ffd100"
            @click="checkedAll"
          ></van-checkbox>
          <span>全选</span>
        </div>
        <div class="controlCar_right">
          <div class="total_price" v-show="accountState == true">
            合计：
            <span>¥&nbsp;{{ getTotal }}</span>
          </div>
          <div class="changeBtn">
            <!-- 结算 -->
            <div class="account" @click="toAccount" v-show="accountState">
              结算
            </div>
            <!-- 删除 -->
            <div class="delCarItem" @click="toDel" v-show="delCarItemState">
              删除
            </div>
          </div>
        </div>
      </div>
      <Footer></Footer>
    </div>
  </div>
</template>

<script>
import Footer from "../components/Footer.vue";
import { mapState, mapMutations } from "vuex";

export default {
  components: {
    Footer,
  },
  data() {
    return {
      checked: false,
      accountState: true, //结算显示状态
      delCarItemState: false, //删除显示状态
      shopCarData: null, //后端获取的购物车数据
      total: 0, //总价
      changePrice: [], //实时价格
      cakeCount: 1,
    };
  },
  created() {
    this.loadCar(this.uid);
  },
  mounted() {},
  methods: {
    // 结算操作
    toAccount() {
      console.log("结算中...");
    },
    toDel() {
      // 设置一个要删除的蛋糕的数量；默认为0
      let toDelCount = 0;
      this.shopCarData.forEach((item, index) => {
        if (item.ischecked == true) {
          toDelCount++;
          this.$dialog
            .confirm({
              message: `确定要将这${toDelCount}个蛋糕删除？`,
            })
            .then(() => {
              // on confirm
              console.log(item.shop_id);
              // this.shopCarData.splice(index, 1);
              this.axios
                .delete(`/shopcart/delCarCake/${item.shop_id}`)
                .then((res) => {
                  console.log(res);
                  location.reload();
                });
            })
            .catch(() => {
              // on cancel
            });
        }
      });
    },
    checkedAll() {
      // console.log(this.checked);
      if (this.checked == true) {
        this.shopCarData.forEach((item, index) => {
          // 判断每个 item 的ischecked是否已经选中
          // 如果是则跳出
          // 否则计算总价
          if (item.ischecked == true) return;

          this.total += item.price;
          item.ischecked = true;
        });
      } else {
        this.shopCarData.forEach((item, index) => {
          // console.log(item);
          this.total -= item.price;
          item.ischecked = false;
        });
      }
    },
    // 改变显示  删除/结算
    changeBtnState() {
      this.accountState = !this.accountState;
      this.delCarItemState = !this.delCarItemState;
    },
    //  改变数量
    // -
    subCount(shop_id, num, event) {
      console.log(event.target.innerHTML);
      let symbol = event.target.innerHTML;
      if (this.shopCarData[num].shop_count == 1) {
        return;
      }
      this.axios
        .put("/shopcart/changeCount", `shopId=${shop_id}&symbol=${symbol}`)
        .then((res) => {
          console.log(res);
        });
      this.shopCarData[num].shop_count--;
      // this.shopCarData[num].price -= this.changePrice[num];
    },
    // +
    addCount(shop_id, num, event) {
      let symbol = event.target.innerHTML;
      console.log(event.target.innerHTML);
      this.axios
        .put("/shopcart/changeCount", `shopId=${shop_id}&symbol=${symbol}`)
        .then((res) => {
          console.log(res);
        });
      this.shopCarData[num].shop_count++;
      // this.shopCarData[num].price += this.changePrice[num];
    },
    loadCar(uid) {
      this.axios.get(`/shopcart/selCart?uid=${uid}`).then((res) => {
        console.log(res);
        if (res.data.code == 200) {
          this.shopCarData = res.data.selCartResult;
        } else {
          return;
        }
        this.shopCarData.forEach((item) => {
          this.changePrice.push(item.price);
        });
      });
    },
    toAddTotal(num) {
      // 定义一个参数保存对 shopCarData的 ischecked是否都为true

      let everyResult = this.shopCarData.every(function (value) {
        return value.ischecked == true;
      });
      // 如果为true，将全选状态变为true
      if (everyResult == true) this.checked = true;
      // 否则为false
      else this.checked = false;

      if (this.shopCarData[num].ischecked == true) {
        this.total += this.shopCarData[num].price;
      } else {
        this.total -= this.shopCarData[num].price;
      }
    },
  },
  computed: {
    ...mapState(["uid"]),
    getTotal() {
      let total = 0;
      this.shopCarData.forEach((item) => {
        if (item.ischecked == true) total += item.price * item.shop_count;
      });
      return total;
    },
    getPrice() {
      return (price, count) => {
        return (price = price * count);
      };
    },
  },
};
</script>
<style scoped src="../assets/css/shoppingcar.css"></style>
<style lang="scss" scoped></style>
